package reittiopas;

import javax.microedition.io.*;
import java.io.*;
import java.util.Vector;

import org.xml.sax.*;

import javax.xml.parsers.*;

/**
*
* @author Jaakko, Petteri
*/

public class RouteService implements IRouteService {
	
	private XMLParser xmlParser;
	
	
	
	public RouteService() {
		xmlParser = new XMLParser();
	}



	
	
	public Vector getRoutes(Location startAddress, Location destAddress, String time, String date,  boolean isStartTime)  { 

		HttpConnection c = null;
		InputStream is = null;
		StringBuffer str = new StringBuffer();
		Vector resultRoutes = null;

		try {
			
			
			//time should be given in format 1030 (user has given: 10:30)
			
			String timeMode = "1"; //default is departure
			if(!isStartTime) {
				timeMode = "2";
			}
			
			
			String requestString = "http://api.reittiopas.fi/public-ytv/fi/api/?a=" + startAddress.getCoordinateX() + "," + startAddress.getCoordinateY()+"&b=" + 
			destAddress.getCoordinateX()+"," + destAddress.getCoordinateY() + 
			"&time=" + time + "&timemode=" + timeMode + "&date=" + date +
			"&user=jazuju&pass=s2fxru4w";
			
			//c = (HttpConnection) Connector.open("http://api.reittiopas.fi/public-ytv/fi/api/?a=" + startAddress.getCoordinateX() + "," + startAddress.getCoordinateY()+"&b=" + destAddress.getCoordinateX()+"," + destAddress.getCoordinateY() + "&user=jazuju&pass=s2fxru4w"); // 2553648,6677498&b=2549445,6675513&user=jazuju&pass=s2fxru4w");
			c = (HttpConnection) Connector.open(requestString);
			System.out.println(requestString);
			
			// Getting the InputStream will open the connection
			// and read the HTTP headers. They are stored until
			// requested.
			is = c.openInputStream();

			// Get the length and process the data
			/*
			 * int len = (int)c.getLength(); int ch; while ((ch = is.read()) !=
			 * -1) { str.append((char)ch); }
			 */

			resultRoutes = xmlParser.getRoutes(is);

			if (is != null)
				is.close();
			if (c != null)
				c.close();

		} catch (IOException e) {
			System.out.print(e);

		} catch (Exception ex) {

		}

		if (resultRoutes != null) {
			getStreetNamesToRoutes(resultRoutes);
			return resultRoutes;
		} else {

			return new Vector(); // Default empty route, maybe because of the
			// errors in generating real one
		}

	} //getROute

	public Location getLocation(String address) {

		HttpConnection connection = null;
		InputStream is = null;
		StringBuffer str = new StringBuffer();
		Route resultRoute = null;
		Vector locations =  null;

		try {

			//if there is a whitespace it should be replaced with '+' because otherwise http request won't be valid 
			//e.g. Mannerheimintie 16->Mannerheimintie+16
			int whiteSpace = address.indexOf(" ");
			if(whiteSpace != -1) {
				address = address.replace(' ', '+');
			}

			//http://api.reittiopas.fi/public-ytv/fi/api/?key=tee&user=nano&pass=test
			String request = "http://api.reittiopas.fi/public-ytv/fi/api/?key=" + address + "&user=jazuju&pass=s2fxru4w";
			System.out.println(request);
			connection = (HttpConnection)Connector.open(request);
			
			is = connection.openInputStream();

			locations = xmlParser.getLocations(is);


			if (is != null)
				is.close();
			if (connection != null)
				connection.close();

		}
		catch(Exception ex) {
			ex.printStackTrace();
		}

		if(locations != null && locations.size() > 0) {
			return (Location)locations.firstElement();
		}
		else {
			return null;
		}
	} 

	/**
	 * Gets the street name for start and destination location.
	 */
	private Vector getStreetNamesToRoutes(Vector routes) {
		for(int j = 0; j < routes.size(); j++) {
			Route route = (Route)routes.elementAt(j);
				getNameForLocation(route.getStartLocation());
				getNameForLocation(route.getDestinationLocation());
		}
		return routes;
	}

	private void setStreetNamesToSubRoute(SubRoute subroute) {

		HttpConnection connection = null;
		InputStream is = null;
		Vector locations =  null;

		try {
			
			Vector intemediateLocations = subroute.getIntermediateLocations();
			Vector allLocations = new Vector();
			allLocations.addElement(subroute.getStartLocation());
			allLocations.addElement(subroute.getDestinationLocation());
			for (int i = 0; i  <intemediateLocations.size(); i ++)
				allLocations.addElement(intemediateLocations.elementAt(i));
			
			for(int i = 0; i<allLocations.size(); i++) {
				Location location = (Location)allLocations.elementAt(i);
				if (location.getAddress() != null)
					continue;

				String x = location.getCoordinateX();
				String y = location.getCoordinateY();	

				x = x.substring(0, 7);
				y = y.substring(0, 7);
				
				String requestString = "http://api.reittiopas.fi/public-ytv/fi/api/?x="+ x + "&y=" + y + "&user=jazuju&pass=s2fxru4w";
				
				connection = (HttpConnection) Connector.open(requestString);
				System.out.println(requestString);

				is = connection.openInputStream();
				locations = xmlParser.getLocations(is);
				
				Location tempLocation = (Location)locations.firstElement();
				location.setAddress(tempLocation.getAddress());
				location.setNumber(tempLocation.getNumber());
				location.setCity(tempLocation.getCity());

				if (is != null)
					is.close();
				if (connection != null)
					connection.close();

			}
		}
		catch(Exception ex) {

		}
	}

	public void getNameForLocation(Location location) {
		if(location.getAddress() != null)  //don't fetch the name again
			return;
		
		HttpConnection connection = null;
		InputStream is = null;
		Vector locations =  null;
		
		String x = location.getCoordinateX();
		String y = location.getCoordinateY();	

		x = x.substring(0, 7);
		y = y.substring(0, 7);

		try {
				String requestString = "http://api.reittiopas.fi/public-ytv/fi/api/?x="+ x + "&y=" + y + "&user=jazuju&pass=s2fxru4w";
				
				connection = (HttpConnection) Connector.open(requestString);
				System.out.println(requestString);

				is = connection.openInputStream();
				locations = xmlParser.getLocations(is);
				
				Location tempLocation = (Location)locations.firstElement();
				location.setAddress(tempLocation.getAddress());
				location.setNumber(tempLocation.getNumber());
				location.setCity(tempLocation.getCity());

				if (is != null)
					is.close();
				if (connection != null)
					connection.close();

			}
			catch(Exception ex) {
				ex.printStackTrace();
			}

	}


} //class


